package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojo.WmMaterial;
import com.heima.model.wemedia.pojo.WmNews;
import com.heima.model.wemedia.pojo.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {


    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
//
//        dto.checkParam();
//
//
//        //条件查询
//        IPage page = new Page(dto.getPage(),dto.getSize());
//        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//
//
//        if(dto.getStatus()!=null){
//            lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
//        }
//        if (dto.getChannelId()!=null){
//            lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
//        }
//        if (dto.getEndPubDate()!=null&&dto.getBeginPubDate()!=null){
//            lambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
//        }
//        if(StringUtils.isNotBlank(dto.getKeyword())){
//            lambdaQueryWrapper.eq(WmNews::getTitle,dto.getKeyword());
//        }
//        lambdaQueryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
//        lambdaQueryWrapper.orderByDesc(WmNews::getPublishTime);
//
//        page = page(page,lambdaQueryWrapper);
//
//        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
//
//        pageResponseResult.setData(page.getRecords());
//        return pageResponseResult;

        dto.checkParam();
        IPage page = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (dto.getStatus()!=null){
            lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        if (dto.getChannelId()!=null){
            lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        if (dto.getBeginPubDate()!=null&&dto.getEndPubDate()!=null){
            lambdaQueryWrapper.between(WmNews::getCreatedTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        if (dto.getKeyword()!=null){
            lambdaQueryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        lambdaQueryWrapper.eq(WmNews::getChannelId,WmThreadLocalUtil.getUser().getId());

        page = page(page,lambdaQueryWrapper);

        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());

        pageResponseResult.setData(page.getRecords());

        return pageResponseResult;

    }

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        if (dto==null||dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmNews wmNews = new WmNews();

        BeanUtils.copyProperties(dto,wmNews);

        if (dto.getImages()!=null&&dto.getImages().size()>0){
            String join = StringUtils.join(dto.getImages(),",");
            wmNews.setImages(join);
        }

        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }


        saveOrUpdateWmNews(wmNews);

        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        List<String> materials = extractUrlInfo(dto.getContent());

        saveRelativeInfoForContent(materials,wmNews.getId());

        //保存文章封面图片与素材的关系
        saveRelativeInfoForCover(dto,wmNews,materials);


        //保存或修改文章
        //判断是否为草稿  如果是结束当前方法
        //不是草稿 保存文章内容图片和素材的关系
        //不是草稿 保存文章封面图片与素材关系


        //wmNewsAutoScanService.autoScanNews(wmNews.getId());
        wmNewsTaskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> materials) {
//
//        List<String> collect = dto.getImages();
//        //封面类型为自动的时候
//        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
//
//            if (materials.size()>=3){
//                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
//                collect = materials.stream().limit(3).collect(Collectors.toList());
//            }else if(materials.size()>=1&&materials.size()<3){
//                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
//                collect = materials.stream().limit(1).collect(Collectors.toList());
//            }else {
//                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
//            }
//
//            //修改图片
//
//            if (collect!=null && collect.size()>0){
//                wmNews.setImages(StringUtils.join(collect,","));
//
//            }
//            updateById(wmNews);
//        }
//        if (collect!=null && collect.size()>0){
//            saveRelativeInfo(collect, wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
//        }
        List<String> images = dto.getImages();
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            if (materials!=null&&materials.size()>3){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = materials.stream().limit(3).collect(Collectors.toList());
            }else if (materials!=null&&materials.size()>=1&&materials.size()<3){
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = materials.stream().limit(1).collect(Collectors.toList());
            }else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            if (images!=null&&images.size()>0){
                wmNews.setImages(StringUtils.join(images,","));
            }
            updateById(wmNews);
        }
        if (images!=null&&images.size()>0){
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
        }



    }

    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {

        
        saveRelativeInfo(materials, newsId,WemediaConstants.WM_CONTENT_REFERENCE);

    }

    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
//        if (materials!=null&&!materials.isEmpty()){
//            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl,materials));
//
//            if (wmMaterials==null||wmMaterials.size()==0){
//                throw new CustomException(AppHttpCodeEnum.MATERIALS_REFERENCE_FAIL);
//            }
//            if(materials.size()!=wmMaterials.size()){
//                throw new CustomException(AppHttpCodeEnum.MATERIALS_REFERENCE_FAIL);
//            }
//
//            List<Integer> collect = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
//            wmNewsMaterialMapper.saveRelations(collect,newsId,type);
//        }

        if (materials!=null&&materials.size()>0){
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
            if (wmMaterials==null||wmMaterials.size()==0){
                throw new CustomException(AppHttpCodeEnum.MATERIALS_REFERENCE_FAIL);
            }
            if (materials.size()!=wmMaterials.size()){
                throw new CustomException(AppHttpCodeEnum.MATERIALS_REFERENCE_FAIL);
            }

            List<Integer> collect = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
            wmNewsMaterialMapper.saveRelations(collect,newsId,type);
        }
    }

    private List<String> extractUrlInfo(String content) {
        ArrayList<String> arrayList = new ArrayList<>();

        List<Map> list = JSON.parseArray(content, Map.class);
        for (Map map : list) {
            if (map.get("type").equals("image")){
                String utl = (String)map.get("value");
                arrayList.add(utl);
            }
        }
        return arrayList;
    }


    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setPublishTime(new Date());
        wmNews.setCreatedTime(new Date());
        wmNews.setStatus((short) 1);
        if (wmNews.getId()==null){
            save(wmNews);
        }else {
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            updateById(wmNews);
        }


    }

    @Autowired
    private WmNewsService wmNewsService;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {

        if (dto.getId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews byId = wmNewsService.getById(dto.getId());
        if (byId==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }

        if (!byId.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章未发布");
        }
        if(byId.getEnable()!=null&&byId.getEnable()>-1&&dto.getEnable()<2){
            update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable,dto.getEnable()).eq(WmNews::getId,byId.getId()));

            if (byId.getArticleId()!=null){
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("articleId",byId.getArticleId());
                hashMap.put("enable",dto.getEnable());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(hashMap));
            }

        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
